// Fill out your copyright notice in the Description page of Project Settings.


#include "AliyunOssLink.h"

#include "alibabacloud/oss/OssClient.h"
#include "alibabacloud/oss/client/ClientConfiguration.h"

using namespace AlibabaCloud::OSS;


FOssClient::FOssClient()
	:ossClient(nullptr)
{
	//AlibabaCloud::OSS::InitializeSdk();	
}

FOssClient::~FOssClient()
{
	if (ossClient)
	{
		delete ossClient;
	}
	//AlibabaCloud::OSS::ShutdownSdk();

	GLog->Log("AlibabaCloud::OSS::ShutdownSdk()");
}

bool FOssClient::IsLink()const
{
	return ossClient != nullptr;
}

bool FOssClient::LinkClient(const FOssOssClientInfo& ClientInfo)
{
	FOssClient& link = FOssClient::Get();
	if (!link.IsLink())
	{
		return link.LinkOssClient(ClientInfo);
	}
	return false;
}


//	static AlibabaCloud::OSS::OssClient& GetClientRef();
AlibabaCloud::OSS::OssClient& FOssClient::GetClientRef()
{
	FOssClient& link = FOssClient::Get();
	check(link.IsLink());
	return *link.ossClient;
}


FOssClient& FOssClient::Get()
{
	static FOssClient ossClient;
	return ossClient;
}


bool FOssClient::LinkOssClient(const FOssOssClientInfo& linkInfo)
{
	//Cannot repeat link
	if (ossClient)return false;
	if (!linkInfo.IsValid())return false;
	info = linkInfo;
	ClientConfiguration conf;
	ossClient =
		new OssClient(TCHAR_TO_UTF8(*info.Endpoint), TCHAR_TO_UTF8(*info.AccessKeyId), TCHAR_TO_UTF8(*info.AccessKeySecret), conf);

	return true;
}


void FOssClient::InitializeSdk()
{
	AlibabaCloud::OSS::InitializeSdk();
}
void FOssClient::ShutdownSdk()
{
	AlibabaCloud::OSS::ShutdownSdk();
}


FString FOssHashOper::GetLocalFileHashString(const FString& InFilename)
{
	if (FPaths::FileExists(InFilename))
	{
		TArray<uint8> arrByte;
		FFileHelper::LoadFileToArray(arrByte, *InFilename);
		return GetFileHashString(arrByte);
	}
	return "";
}

FString FOssHashOper::GetFileHashString(const TArray<uint8>& arrByte)
{
	return FMD5::HashBytes(arrByte.GetData(), arrByte.Num());
}

FString FOssHashOper::GetCloudFileHashString(const FString& InFilename)
{
	FString bucketName;
	FString objectKey;
	//if (!FAliyunOssTaskInfo::TransformationPathToBucketAndKey(InFilename, bucketName, objectKey))
	//{
	//	return "";
	//}
	return GetCloudFileHashString(bucketName, objectKey);
}

FString  FOssHashOper::GetCloudFileHashString(const FString& bucketName, const FString& objectKey)
{
	if (bucketName.Len() * objectKey.Len() <= 3)
	{
		return "";
	}

	ObjectMetaDataOutcome objectMeta = FOssClient::GetClientRef().GetObjectMeta(TCHAR_TO_UTF8(*bucketName), TCHAR_TO_UTF8(*objectKey));
	const ObjectMetaData& result = objectMeta.result();
	return UTF8_TO_TCHAR(result.ETag().c_str());
}